package com.service;

import com.entity.ElderMonthlyFinance;
import com.repository.ElderMonthlyFinanceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class ElderMonthlyFinanceService {

    @Autowired
    private ElderMonthlyFinanceRepository elderMonthlyFinanceRepository;

    /**
     * 保存月度财务信息
     * @param elderMonthlyFinance 月度财务信息
     * @return 保存后的对象
     */
    public ElderMonthlyFinance save(ElderMonthlyFinance elderMonthlyFinance) {
        if (elderMonthlyFinance.getId() == null) {
            elderMonthlyFinance.setCreateTime(new Date());
        }
        elderMonthlyFinance.setUpdateTime(new Date());
        elderMonthlyFinance.setBalance(elderMonthlyFinance.getIncomeAmount().subtract(elderMonthlyFinance.getExpenseAmount()));
        return elderMonthlyFinanceRepository.save(elderMonthlyFinance);
    }

    /**
     * 根据ID删除月度财务信息
     * @param id ID
     */
    public void deleteById(Integer id) {
        elderMonthlyFinanceRepository.deleteById(id);
    }

    /**
     * 根据ID获取月度财务信息
     * @param id ID
     * @return 月度财务信息
     */
    @Transactional(readOnly = true)
    public Optional<ElderMonthlyFinance> findById(Integer id) {
        return elderMonthlyFinanceRepository.findById(id);
    }

    /**
     * 分页查询月度财务信息
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<ElderMonthlyFinance> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return elderMonthlyFinanceRepository.findAll(pageable);
    }
}